/*
* 判断是否登录
* 公用配置/方法
* */

import Vue from 'vue'
import router from '../router'
import {URL0,URL1} from './baseUrl'
import axios from 'axios'
const Qs = require('qs');

// import COS from 'cos-nodejs-sdk-v5'
// 引入模块
// import {COS} from 'cos-nodejs-sdk-v5'
// const COS = require('cos-nodejs-sdk-v5');
// 创建实例
// const cos = new COS({
//     AppId: '1250000000',
//     SecretId: 'AKIDxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
//     SecretKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
// });

axios.defaults.withCredentials = true;
// 供应商
const config0 = {
  pdata: {ws: {}},
  isLogin: () => {
    return new Promise((resolve, reject) => {
      axios(URL0 + '/user/info').then(res => {
        if (res.data.code === 1) {
          resolve(true);
        } else {
          reject(false);
        }
      })
    });
  },
  fileUrl: 'https://dlhz.oss-cn-beijing.aliyuncs.com/',
  toUrl: (obj) => {
    let str = '';
    for (let i in obj) {
      str += '&' + i + '=' + obj[i] || '';
    }
    str = str.substr(1);
    return str;
  },
  get: (url, obj) => {
    return axios.get(URL0 + url + '?' + config0.toUrl(obj));
  },
  post: (url, obj) => {
    return axios.post(URL0 + url + '?' + config0.toUrl(obj));
  },
  post3: (url, obj) => {
    return axios({
      url:URL0+url,
      method: 'post',
      data: Qs.stringify(obj),
      // headers:{
      //   'Content-Type':'application/json;charse=UTF-8'
      // },
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
    });
  },
  post2: (url, obj) => {
    // return axios.post('http://192.168.0.105:8085'+ url + '?' + config0.toUrl(obj));
    return axios.post(URL0.substring(0,(URL0.length-4))+ url + '?' + config0.toUrl(obj));
  },
  // 处理错误信息
  handleError: (data) => {
    if (data.code === '-3001') {
      return data.message;
    } else if (data.code === '-2001') {
      router.push({path: '/project0/login'});
      // router.push({path: '/login'});
      // return '未登录';
    } else if (data.code === '-1001' || data.code === '-1002') {
      return data.message;
    } else {
      return data.message;
    }
  },
  // 获取微信授权的信息
  getWxInfo() {
    // 链接websocket
    // Vue.use(VueWebsocket, 'ws://interface.xiao2yun.com:12315?openid='+info.uInfo.open_id+'&merchant_id='+info.tInfo.mid+'&tid='+info.tInfo.tid+'&type=weixindiancan');
    let info1 = this.GetRequest();
    if(info1.mid){
      sessionStorage.setItem('yamiQrcodeAuthorInfo', JSON.stringify(info1));
      location.href = location.href.split('?')[0];
    }else{
      let info = JSON.parse(sessionStorage.getItem('yamiQrcodeAuthorInfo'));
      if(info.mid){
        this.globalInfo.mid = info.mid;
        this.globalInfo.tid = info.tid;
        this.globalInfo.code = info.code || '';
        this.globalInfo.authCode = info.authCode || '';
        this.authorLogin();
      }
    }
    // this.globalInfo.mid = info1.mid;
    // this.globalInfo.tid = info1.tid;
    // this.globalInfo.code = info1.code || '';
    // // this.getToken();
    // this.authorLogin();

  },
  getLoginInfo(){
      // this.globalInfo.user = JSON.parse(sessionStorage.getItem('xpjLoginInfo')) || {};
    this.post('/user/info', {}).then(res=>{
      if(res.data.status===1){
        this.globalInfo.user = res.data.data;
        this.wsConnect();
      } else {
        if(!this.$router) return;
        this.$router.push('/page/login');
      }
    })
  },
  // 储存微信授权的信息
  globalInfo: {
    "mid": '5c85dc7c-5a4a-418e-bcb3-37afffa25629',
    "tid": '6f518d5b-24cd-49ed-8d96-a98bcceca39b',
    "code": '',
    "authCode": '',
    "user": {
    },
    "merchantInfo": {
      "is_pre_meal_pay": '', // 0先下单后付款  1先付款后下单
      "is_open_auditing": '', // 0扫码下单审核开启  1扫码下单审核关闭
      "is_allow_user_pay": '', // 0顾客付款关闭  1顾客付款开启
    },
    "ladyInfo": {
    }
    // token: 'e0bb5702ba4d4acea65ad1a668458223',
  },
  // websocket链接
  wsConnect() {
    let info = this.globalInfo;
    // let ws = new WebSocket('ws'+URL.substr(4)+'/myWebSocket/'+info.user.id);
    // let ws = new WebSocket('ws://192.168.0.132:12315?openid='+(this.globalInfo.user.open_id||this.globalInfo.user.user_id)+'&merchant_id='+this.globalInfo.mid+'&tid='+this.globalInfo.tid+'&type=weixindiancan');
    // let ws = new WebSocket('ws' + URL.substr(4) + ':12315?openid='+(this.globalInfo.user.open_id||this.globalInfo.user.user_id)+'&merchant_id='+this.globalInfo.mid+'&tid='+this.globalInfo.tid+'&type=weixindiancan');
    ws.onopen = (evt) => {
      this.onOpen(evt)
    };
    ws.onclose = (evt) => {
      this.onClose(evt)
    };
    ws.onmessage = (evt) => {
      if (typeof evt.data !== 'string') {
        let reader = new FileReader();
        reader.onload = (eve) => {
          this.onMessage(JSON.parse(eve['target']['result']));
        };
        reader.readAsText(evt.data, 'utf-8');
      }
    };
    ws.onerror = (evt) => {
      this.onError(evt)
    };

    this.pdata.ws = ws;
  },
  onOpen(evt) {
  },
  onClose(evt) {
    this.wsConnect();
  },
  onMessage(evt) {
  },
  onError(evt) {
  },
  getWs() {
    return this.pdata.ws;
  },

};
// =====================================================================================================================
// 采购商
const config1 = {
  pdata: {ws: {}},
  isLogin: () => {
    return new Promise((resolve, reject) => {
      axios(URL1 + '/user/info').then(res => {
        if (res.data.code === 1) {
          resolve(true);
        } else {
          reject(false);
        }
      })
    });
  },
  fileUrl: 'https://dlhz.oss-cn-beijing.aliyuncs.com/',
  toUrl: (obj) => {
    let str = '';
    for (let i in obj) {
      str += '&' + i + '=' + obj[i] || '';
    }
    str = str.substr(1);
    return str;
  },
  get: (url, obj) => {
    return axios.get(URL1 + url + '?' + config1.toUrl(obj));
  },
  post: (url, obj) => {
    return axios.post(URL1 + url + '?' + config1.toUrl(obj));
  },
  post2: (url, obj) => {
    // return axios.post('http://192.168.0.105:8085'+ url + '?' + config1.toUrl(obj));
    return axios.post(URL1.substring(0,(URL1.length-4))+ url + '?' + config1.toUrl(obj));
  },
  // 处理错误信息
  handleError: (data) => {
    if (data.code === '-3001') {
      return data.message;
    } else if (data.code === '-2001') {
      router.push({path: '/project1/login'});
      return data.message;
    } else if (data.code === '-1001' || data.code === '-1002') {
      return data.message;
    } else {
      return data.message;
    }
  },
  // 所有分类菜品信息
  allFood: [],
  //购物车
  cart: [],
  // 总价
  orderPrice: 0,

  // 当前在用餐桌信息
  currentTableInfo: {},

  // 是否是加菜状态
  isAddFood: false,

  //积分购物车
  cart2: {},

  // 分类页储存分类id和商品数据
  classStore: {},
  getLoginInfo(){
      // this.globalInfo.user = JSON.parse(sessionStorage.getItem('xpjLoginInfo')) || {};
    this.post('/purchasers/app/basic/getLoginInfo', {}).then(res=>{
      if(res.data.code==0){
        this.globalInfo.user = res.data.purchasersUser;
        // this.wsConnect();
      } else {
        if(!this.$router) return;
        this.$router.push('/page/login');
      }
    })
  },
  // 储存微信授权的信息
  globalInfo: {
    "mid": '5c85dc7c-5a4a-418e-bcb3-37afffa25629',
    "tid": '6f518d5b-24cd-49ed-8d96-a98bcceca39b',
    "code": '',
    "authCode": '',
    "user": {
    },
    "merchantInfo": {
      "is_pre_meal_pay": '', // 0先下单后付款  1先付款后下单
      "is_open_auditing": '', // 0扫码下单审核开启  1扫码下单审核关闭
      "is_allow_user_pay": '', // 0顾客付款关闭  1顾客付款开启
    },
    "ladyInfo": {
    }
    // token: 'e0bb5702ba4d4acea65ad1a668458223',
  },
  // websocket链接
  wsConnect() {
    let info = this.globalInfo;
    // let ws = new WebSocket('ws'+URL.substr(4)+'/myWebSocket/'+info.user.id);
    // let ws = new WebSocket('ws://192.168.0.132:12315?openid='+(this.globalInfo.user.open_id||this.globalInfo.user.user_id)+'&merchant_id='+this.globalInfo.mid+'&tid='+this.globalInfo.tid+'&type=weixindiancan');
    // let ws = new WebSocket('ws' + URL.substr(4) + ':12315?openid='+(this.globalInfo.user.open_id||this.globalInfo.user.user_id)+'&merchant_id='+this.globalInfo.mid+'&tid='+this.globalInfo.tid+'&type=weixindiancan');
    ws.onopen = (evt) => {
      this.onOpen(evt)
    };
    ws.onclose = (evt) => {
      this.onClose(evt)
    };
    ws.onmessage = (evt) => {
      if (typeof evt.data !== 'string') {
        let reader = new FileReader();
        reader.onload = (eve) => {
          this.onMessage(JSON.parse(eve['target']['result']));
        };
        reader.readAsText(evt.data, 'utf-8');
      }
    };
    ws.onerror = (evt) => {
      this.onError(evt)
    };

    this.pdata.ws = ws;
  },
  b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, (match, p1)=> {
      return String.fromCharCode('0x' + p1);
    }));
  },
  // blurR: '?x-oss-process=image/blur,r_50,s_50/watermark,size_65,t_100,color_f0f0f0,text_'+this.b64EncodeUnicode('付费照片'), // oss图片模糊化
  onOpen(evt) {
  },
  onClose(evt) {
    this.wsConnect();
  },
  onMessage(evt) {
  },
  onError(evt) {
  },
  getWs() {
    return this.pdata.ws;
  },

};
// config.getLoginInfo();
const vueMethod = {};

export {config0, config1, vueMethod};
